<template>
  <el-dialog v-el-drag-dialog :title="!form.id?'添加关联商品':'编辑关联商品'" :close-on-click-modal="true" :visible.sync="visible" :append-to-body="appendToBody">
    <el-form ref="form" :model="form" label-width="120px" :disabled="!hasLoaded">
      <el-card>
        <el-form-item label="商品" prop="skuName">
          <el-select
            v-model="form.skuId"
            v-el-select-load-more="loadMoreProductQuery"
            ref="product_select"
            filterable
            remote
            reserve-keyword
            placeholder="请输入商品标题"
            :remote-method="onSearchProduct"
            :loading="loadingQuery">
            <el-option
              v-for="item in productOptions"
              :key="item.skuId"
              :label="item.skuName"
              :value="item.skuId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀价格" prop="seckillPrice">
          <el-input-number v-model="form.seckillPrice" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="秒杀总量" prop="seckillCount">
          <el-input-number v-model="form.seckillCount" :min="1" />
        </el-form-item>
        <el-form-item label="每人限购数量" prop="seckillLimit">
          <el-input-number v-model="form.seckillLimit" :min="1" />
        </el-form-item>
        <el-form-item label="排序" prop="seckillSort">
          <el-input v-model="form.seckillSort" placeholder="排序" />
        </el-form-item>
      </el-card>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { seckillRelationLoad, seckillRelationSave } from '@/api/mall/seckill/relation'
import { skuSelect } from '@/api/mall/product/sku'

export default {
  name: 'SeckillSessionDialog',
  directives: {
    'el-select-load-more': {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECT_WRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECT_WRAP_DOM.addEventListener('scroll', function() {
          /**
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      form: {
        id: undefined,
        sessionId: undefined,
        skuId: undefined,
        skuName: undefined,
        seckillPrice: 0,
        seckillCount: 1,
        seckillLimit: 1,
        seckillSort: 0
      },
      loadingQuery: false,
      productQueryTerm: undefined,
      productQueryPage: 1,
      productQueryLength: 20,
      productQueryMore: false,
      productOptions: []
    }
  },
  methods: {
    init(sessionId, id) {
      this.hasLoaded = false
      this.form.id = id
      this.form.sessionId = sessionId
      this.productOptions = []
      this.visible = true
      this.$nextTick(() => {
        this.loadForm(sessionId, id)
      })
    },
    loadForm(sessionId, id) {
      seckillRelationLoad({ 'id': id, 'sessionId': sessionId }).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        this.loadProduct()
        // 判断当前用户权限
        this.hasLoaded = this.$perm.hasPermissionOr(['mall:seckill:edit'])
      }).catch(() => {
      })
    },
    loadProduct() {
      if (this.form.skuId && this.form.skuName) {
        this.$refs.product_select.cachedOptions.push({
          currentLabel: this.form.skuName, // 	当前绑定的数据的label
          currentValue: this.form.skuId, // 当前绑定数据的value
          label: this.form.skuName, // 当前绑定的数据的label
          value: this.form.skuId // 当前绑定数据的value
        })
      }
    },
    onSearchProduct(query) {
      this.loadingQuery = true
      this.productQueryPage = 1
      this.productQueryTerm = query
      this.productOptions = []
      this.getProductQueryData()
      this.productQueryPage++
      this.loadingQuery = false
    },
    getProductQueryData() {
      skuSelect({
        term: this.productQueryTerm, // 输入值
        page: this.productQueryPage, // 页码
        length: this.productQueryLength
      }).then(response => {
        this.productOptions = [...this.productOptions, ...response.param.data]
        this.productQueryMore = (this.productQueryPage * this.productQueryLength) < response.param.total
      }).catch(e => {})
    },
    loadMoreProductQuery() {
      if (this.productQueryMore) {
        this.productQueryPage++
        this.getProductQueryData()
      }
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          seckillRelationSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.onClose()
          }).catch(() => {
          })
        }
      })
    },
    onClose() {
      this.$refs.form.resetFields()
      this.visible = false
    }
  }
}
</script>
